function tool_tx_manager
% display('3: tx manager');

% global model LN xmin xmax zmin zmax precision xx ZZ vinerror selectL scolor slswitch

% *******************************
%% Variables for whole function
% *******************************
%--- OBS
% "OBS" is a 1xn structure array to store OBS information, each OBS (source in tx.in file) is a element of "OBS"
% header(structure field) name list
% name: source name, like 'obs33a'; string
% XYZ: UTM coordinates, depth and scale to meters; [1x4]
% LatLon: latitude and longitude in degree; [1x2]
% moffset: OBS location (offset) in the model in km; scalar
% phase: a cell, each element is a picked event, which is stored in n-by- matrix format, the columns are (the first 4 are identical to tx.in sequence)
%        (1-4) receiver model offset, travel time, uncertainty, new defined travel time group (a normal non-zero integer), (5) the original group number in tx.in,
%        (6) travel direction in the model (-1 for left, 1 for right), (7) model layer number of the phase,
%        (8) ray code (1 refraction, 2 reflection, 3 head wave), (9) wave type (1 P-wave, 2 PS-wave),
%        (10) shot number of picking, (11) original pick time, (12) time correction to make tx.in
% phaseID: a 2-by-phase number integer matrix; row 1 are between 100-999, generated by order for both OBS and SCS when the unique phase made and stored in phasecollection;
%          when a correponding phase deleted, the ID also be cleared and will not use again. Row 2 are normally between 1-99, no-repeat for the model to identify time group for the
%          same layer and same ray code
% phasefile: 1-by-phase number strings, record the source file when the phase data were imported
% remarks: 1-by-phase number strings, for simple explanation words
% offsettable: shot number vs. model offset table, a n-by- matrix, columns are (1) shot number, (2) model offset in km
% tablefile: The corresponding source file of offsettable, a string, each OBS has its own table; the source txt file may have information to indicate itself is a OBS,
%            that is the first line can be -moffset and moffset, then following the shot number and model offset pairs.
OBS=struct('name','','XYZ',NaN(1,4),'LatLon',NaN(1,2),'moffset',NaN,'phase',{},'phaseID',{},'phasefile',{},'remarks',{},'offsettable',{},'tablefile','');

%--- SCS
% "SCS" is also a 1xn structure array, each survey is a element
% name: different than OBS, here is survey name, like 'scsLine4a'; string
% shot_rec: shot receiver offset, refer to tablefile
% phase: a cell, each element is a picked event, which is stored in n-by- matrix format, the columns are (the first 4 are identical to tx.in sequence)
%        (1-4) receiver model offset, travel time, uncertainty, new difined travel time group (a normal non-zero integer), (5) the original group number in tx.in,
%        (6) travel direction in the model (-1 for left, 1 for right), (7) model layer number of the phase,
%        (8) ray code (1 refraction, 2 reflection, 3 head wave), (9) wave type (1 P-wave, 2 PS-wave),
%        (10) shot number of picking, (11) original pick time, (12) time correction to make tx.in
% phaseID: a 2-by-phase number integer matrix; row 1 are between 100-999, generated by order for both OBS and SCS when the unique phase made and stored in phasecollection;
%          when a correponding phase deleted, the ID also be cleared and will not use again. Row 2 are normally between 1-99, no-repeat for the model to identify time group for the
%          same layer and same ray code
% phasefile: 1-by-phase number strings, record the source file when the phase data were imported
% remarks: 1-by-phase number strings, for simple explanation words
% offsettable: shot number vs. model offset table, a n-by- matrix, columns are (1) shot number, (2) model offset in km
% tablefile: The corresponding source file of offsettable, a string, not like OBS, here each survey has a table; the source txt file may have information
%          to indicate itself is a SCS survey, that is the first line is 2 identical negative value, the offset of receiver behind the shot; or -999 and 0 for
%          ideal vertical incidence
SCS=struct('name','','shot_rec',NaN,'phase',{},'phaseID',{},'phasefile',{},'remarks',{},'offsettable',{},'tablefile','');

%--- phase group stores the information of tx.in template made/used in menu "Plot & select phases to make tx.in"
% "phasegroup" is a 1xn structure array, used to store phases selected to plot travel time and output tx.in file
% name: user defined name for each group
% OBS: a 6-by-phase number matrix, the rows are (1) phase ID, (2) time group, (3) OBS#, (4) OBS#.moffset, (5) phase number in OBS#, (6) direction: left -1, right 1, both 2
% SCS: a 5-by-phase number matrix, the rows are (1) phase ID, (2) time group, (3) SCS#, (4) shot_rec offset, (5) phase number in SCS#
phasegroup=struct('name',{},'OBS',{},'SCS',{});

phasecollection=[]; % a unique integer vector (between 100-999) store all phases' ID, including OBS and SCS
phaseIDused=99; % increase 1 each time a new phase produced, but will not decrease
timegroup={}; % hold the 1-by-n vectors of phaseID; each phaseID can only be in one vector; the phases in one time group share the same layer and ray code and wave type

%--- constants
modelorigin=[NaN NaN];  % x and y in meters
modelstrike=NaN; % the direction of 2D model profile, in degree
phasecolname={'Receiver dist. (km)','Travel time (s)','Uncertainty','Group','Orig. group','Direction','Model layer','Ray type','Wave type',...
    'Shot number','Orig. pick','Time correct'};
phasecolnumber=12; % column length of the phase matrix defined for OBS and SCS


% initial file path and names
[loadpath,loadname,savepath,savename,fullload,fullsave,previoustxin,preofftablepath,prepickpath]=deal('');
alreadyload=0;

% variables to save to history_vin.mat
save_list = {'loadpath','loadname','fullload','savepath','savename','fullsave',...
    'previoustxin','preofftablepath','prepickpath','modelorigin','modelstrike',...
    'OBS','SCS','phasegroup','phasecollection','phaseIDused','timegroup'};

% load last run information
if exist('history_txmanager.fig','file')
    txmh = openfig('history_txmanager.fig');
end
if exist('history_txmanager.mat','file');
    s=load('history_txmanager.mat');
    loadpath=s.loadpath;
    loadname=s.loadname;
    fullload=s.fullload;
    savepath=s.savepath;
    savename=s.savename;
    fullsave=s.fullsave;
    previoustxin=s.previoustxin;
    preofftablepath=s.preofftablepath;
    prepickpath=s.prepickpath;
end
if isempty(fullload);
    loadprevious='off';
else
    loadprevious='on';
end
s=[];

% inpath='e:\Researches\CanadaWorks\subbarao\for-Tao\30dec\';
% inpath='e:\Researches\CanadaWorks\subbarao\for-Tao\';
% inpath='e:\Researches\CanadaWorks\rdash\CAS1B\RayInvr\swave_modeling\';
% inname='tx.in';
% inname='tx_all.in';
% filein=fullfile(inpath,inname);


%% UI
if exist('txmh','var') && ishandle(txmh)
    % txmh = 3;
    % set(txmh,'Visible','on');
    figure(txmh);
else
    txmh = figure();
    set(txmh,'Visible','off','Name','tx manager','MenuBar','none',...
        'NumberTitle','on','Position',[10,10,1300,700]);
   %% menu item
    menuh1 = uimenu(txmh,'Label','Database (*_tx.mat)','position',1);
    uimenu(menuh1,'Label','Load database','Callback',@load_callback);
    ch12=uimenu(menuh1,'Label','Load last used database','Callback',@load_callback,'Enable',loadprevious);
    ch13=uimenu(menuh1,'Label','Save database','Tag','save','Callback',@save_callback,'Enable','off');
    ch14=uimenu(menuh1,'Label','Save current database as','Tag','saveas','Callback',@save_callback,'Enable','off');
    ch15=uimenu(menuh1,'Label','Export database to text','Callback',@export_callback,'Enable','off');
    ch16=uimenu(menuh1,'Label','Create by import tx.in','Separator','on','Callback',@createbytxin_callback,'Enable','on');
    ch18=uimenu(menuh1,'Label','Create by import (batch) shot-model distance table','Tag','create','Callback',@importoffset_callback,'Enable','on');
    uimenu(menuh1,'Label','Quit','Callback','exit','Separator','on');

    menuh2 = uimenu(txmh,'Label','OBS','position',2);
%     ch21=uimenu(menuh2,'Label','View ...','Callback','','Enable','off');
    ch23=uimenu(menuh2,'Label','Import (batch) OBS shot-model distance table','Tag','OBS','Callback',@importoffset_callback,'Enable','off');
    ch24=uimenu(menuh2,'Label','Maintain ...','Callback',@maintain_callback,'Enable','off');

    menuh3 = uimenu(txmh,'Label','SCS','position',3);
%     ch31=uimenu(menuh3,'Label','View ...','Callback','','Enable','off');
%     ch32=uimenu(menuh3,'Label','Add phases by import picks','Callback',@importpicks_callback,'Enable','off');
    ch33=uimenu(menuh3,'Label','Import SCS shot-model distance table into current survey','Tag','SCS','Callback',@importoffset_callback,'Enable','off');
    ch34=uimenu(menuh3,'Label','Maintain ...','Callback',@maintain_callback,'Enable','off');

    menuh4 = uimenu(txmh,'Label','Make','position',4);
    ch41=uimenu(menuh4,'Label','Import new tx.in and merge into current database','Callback',@addtxin_callback,'Enable','off');
    ch42=uimenu(menuh4,'Label','Add OBS/SCS phase picks','Callback',@importpicks_callback,'Enable','off');
    ch43=uimenu(menuh4,'Label','Group phase time with plot','Separator','on','Callback',@timegrouptool_callback,'Enable','off');
    ch44=uimenu(menuh4,'Label','Plot & select phases to make tx.in','Callback',@maketxtool_callback,'Enable','off');

    menuh5 = uimenu(txmh,'Label','Debug','position',5);
    ch51=uimenu(menuh5,'Label','Export virables to base workspace','Callback',@debug_callback,'Enable','off');

    menuh6 = uimenu(txmh,'Label','Help','position',6,'Enable','on');
    uimenu(menuh6,'Label','Read me','Tag','readme','Callback',@help_callback);
    uimenu(menuh6,'Label','About','Tag','about','Callback',@help_callback);

   %% panels
    % control panel
    controlp = uipanel(txmh,'Visible','off','Position',[.81 .0 .19 1],'FontSize',12);
    % model panel
    modelp = uipanel(controlp,'Title','Model information','TitlePosition','centertop','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.025 .85 .95 .15]);
    uicontrol(modelp,'Style','text','String','Origin X:','HorizontalAlignment','right','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.0 .7 .35 .2]);
    oxh=uicontrol(modelp,'Style','edit','Tag','ox','String',num2str(modelorigin(1)),'HorizontalAlignment','center','FontWeight','bold','FontSize',10,...
        'Callback',@edit_callback,'Units','normalized','Position',[.355 .7 .345 .2]);
    uicontrol(modelp,'Style','text','String','(m)','HorizontalAlignment','left','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.70 .7 .3 .2]);
    uicontrol(modelp,'Style','text','String','Y:','HorizontalAlignment','right','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.0 .4 .35 .2]);
    oyh=uicontrol(modelp,'Style','edit','Tag','oy','String',num2str(modelorigin(2)),'Callback',@edit_callback,'HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.355 .4 .345 .2]);
    uicontrol(modelp,'Style','text','String','(m)','HorizontalAlignment','left','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.7 .4 .3 .2]);
    uicontrol(modelp,'Style','text','String','Strike:','HorizontalAlignment','right','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.0 .1 .35 .2]);
    strikeh=uicontrol(modelp,'Style','edit','Tag','strike','String',num2str(modelstrike),'Callback',@edit_callback,'HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.355 .1 .345 .2]);
    uicontrol(modelp,'Style','text','String','degree','HorizontalAlignment','left','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.7 .1 .3 .2]);
    % OBS/SCS display switch
    bgh = uibuttongroup(controlp,'Title','Display','FontWeight','bold','FontSize',12,'Position',[.025 .73 .95 .12],'SelectionChangeFcn',@bgh_SelectionChangeFcn);
    rbh1 = uicontrol(bgh,'Style','radiobutton','String','OBS','Tag','OBS','Enable','off','Units','normalized','Position',[.1 .45 .8 .5],'FontWeight','bold','FontSize',12,'ForegroundColor','red');
    rbh2 = uicontrol(bgh,'Style','radiobutton','String','SCS','Tag','SCS','Enable','off','Units','normalized','Position',[.1 .05 .8 .5],'FontWeight','bold','FontSize',12,'ForegroundColor','blue');
    % scs panel
    scsp = uipanel(controlp,'Visible','off','Units','normalized','Position',[.025 .0 .95 .725]);
    uicontrol(scsp,'Style','text','String','Select Survey','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.1 .95 .8 .04],'ForegroundColor','blue');
    scspop1 = uicontrol(scsp,'Style','popupmenu','String',' ','Tag','name','Units','normalized','Position',[.1 .91 .8 .03],'FontSize',10,'Callback',@scspop1_callback);
    uicontrol(scsp,'Style','text','String','Select Phase','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.1 .85 .8 .03],'ForegroundColor','blue');
    scspop2 = uicontrol(scsp,'Style','popupmenu','String',' ','Tag','phase','Units','normalized','Position',[.1 .81 .8 .03],'FontSize',10,'Callback',@scspop2_callback);
    uicontrol(scsp,'Style','text','String','Shot number vs. model distance table','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.1 .71 .8 .06],'ForegroundColor','blue');
    scsofftableh=uitable(scsp,'Units','normalized','Position',[.0 .0 1 .7],'ColumnName',{'Shot','Distance (km)'},'ColumnWidth',{50 90},'FontSize',10);
    % obs panel
    obsp = uipanel(controlp,'Visible','off','Units','normalized','Position',[.025 .0 .95 .725]);
    uicontrol(obsp,'Style','text','String','Select OBS','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.1 .95 .8 .04],'ForegroundColor','red');
    obspop1 = uicontrol(obsp,'Style','popupmenu','String',' ','Tag','name','Units','normalized','Position',[.1 .91 .8 .03],'FontSize',10,'Callback',@obspop1_callback);
    uicontrol(obsp,'Style','text','String','Select Phase','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.1 .85 .8 .03],'ForegroundColor','red');
    obspop2 = uicontrol(obsp,'Style','popupmenu','String',' ','Tag','phase','Units','normalized','Position',[.1 .81 .8 .03],'FontSize',10,'Callback',@obspop2_callback);
    uicontrol(obsp,'Style','text','String','Shot number vs. model distance table','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.1 .71 .8 .06],'ForegroundColor','red');
    obsofftableh=uitable(obsp,'Units','normalized','Position',[.0 .0 1 .7],'ColumnName',{'Shot','Distance (km)'},'ColumnWidth',{50 90},'FontSize',10);

    % display panel template
    displayp = uipanel(txmh,'Visible','off','Position',[.0 .0 .81 1]);
    % general information panel
    generalp = uipanel(displayp,'Visible','on','Position',[.0 .85 1 .15]);
    uicontrol(generalp,'Style','text','String','OBS #  ','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.02 .75 .2 .15]);
    uicontrol(generalp,'Style','text','String','Name:  ','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.22 .75 .2 .15]);
    uicontrol(generalp,'Style','text','String','Distance in model:  (km)','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.43 .75 .2 .15]);
    uicontrol(generalp,'Style','text','String','Phase number:  (P: ; S: )','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.66 .75 .25 .15]);
    uicontrol(generalp,'Style','text','String','Latitude:   ; Longitude:   (degree)','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.1 .5 .4 .2]);
    uicontrol(generalp,'Style','text','String','X:     ; Y:     ; Z:    (m)','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.6 .5 .3 .2]);
    uicontrol(generalp,'Style','text','String','Shot number vs. model distance table source file: "   "','HorizontalAlignment','left','FontSize',10,'Units','normalized','Position',[.05 .15 0.9 .25]);
    % phase table
    uicontrol(displayp,'Style','text','String','OBS # : (km)   Phase * is selected','HorizontalAlignment','center','FontWeight','bold','FontSize',12,'Units','normalized','Position',[.35 .81 .3 .03]);
    uicontrol(displayp,'Style','text','String','Source file: "   "','HorizontalAlignment','left','FontSize',10,'Units','normalized','Position',[.05 .74 0.9 .06]);
    uitable(displayp,'Units','normalized','Position',[.0 .0 1 .69],'ColumnName',phasecolname);

    % OBS display panel
    obsdisplayp = uipanel(txmh,'Visible','off','Position',[.0 .0 .81 1]);  % Can get all handles by get(obsdisplayp,'children'). Note: the final one has the first indice since it's on the top
    % general information panel
    obsgeneralp = uipanel(obsdisplayp,'Visible','on','Position',[.0 .85 1 .15]);
    uicontrol(obsgeneralp,'Style','text','String','OBS #   ','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.01 .75 .11 .2],'ForegroundColor','red');
    uicontrol(obsgeneralp,'Style','text','String','Name:  ','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.12 .75 .2 .2],'ForegroundColor','red');
    uicontrol(obsgeneralp,'Style','text','String','Distance in model:  (km)','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.33 .75 .2 .2],'ForegroundColor','red');
    uicontrol(obsgeneralp,'Style','text','String','Phase number:  (P: ; S: )','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.56 .75 .32 .2],'ForegroundColor','red');
    obspop3=uicontrol(obsgeneralp,'Style','popup','String',{'OBS name','[ X Y Z Scale ]','[ Latitude Longitude ]','Pick uncertainty (s)','Model layer',...
        'Ray type (1 refraction, 2 refelction, 3 head wave','Wave type (1 P-wave, 2 S-wave)','Time correction (s)','Delete whole line'},...
        'FontWeight','bold','FontSize',10,'Units','normalized','Position',[.89 .79 .1 .2],'Callback','');
    uicontrol(obsgeneralp,'Style','text','String','Latitude:   ; Longitude:   (degree)','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.02 .45 .3 .2]);
    uicontrol(obsgeneralp,'Style','text','String','X:     ; Y:     ; Z:    (m)','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.34 .45 .32 .2]);
    obsinputh=uicontrol(obsgeneralp,'Style','edit','String','','HorizontalAlignment','center','FontSize',10,'Units','normalized','Position',[.69 .45 .3 .2]);
    uicontrol(obsgeneralp,'Style','text','String','Shot number vs. model distance table source file: "   "','HorizontalAlignment','left','FontSize',10,'Units','normalized','Position',[.05 .1 0.83 .3]);
    uicontrol(obsgeneralp,'Style','pushbutton','String','Set','Tag','OBS','HorizontalAlignment','center','FontWeight','bold','FontSize',10,...
        'Callback',@setvalue_callback,'Units','normalized','Position',[.89 .15 .1 .25],'ForegroundColor','red');
    % phase table
    uicontrol(obsdisplayp,'Style','text','String','OBS # : (km)','HorizontalAlignment','right','FontWeight','bold','FontSize',12,'Units','normalized','Position',[.0 .82 .49 .025],'ForegroundColor','red');
    obsphasetexth=uicontrol(obsdisplayp,'Style','text','String','Phase # is selected','HorizontalAlignment','left','FontWeight','bold','FontSize',12,'Units','normalized','Position',[.51 .82 .49 .025],'ForegroundColor','red');
    obsphasesourceh=uicontrol(obsdisplayp,'Style','text','String','Source file: "   "','HorizontalAlignment','left','FontSize',10,'Units','normalized','Position',[.05 .76 0.9 .05]);
    obsphaseh=uitable(obsdisplayp,'Units','normalized','Position',[.0 .0 1 .76],'ColumnName',phasecolname);

    % SCS display panel
    scsdisplayp = uipanel(txmh,'Visible','off','Position',[.0 .0 .81 1]);
    % general information panel
    scsgeneralp = uipanel(scsdisplayp,'Visible','on','Position',[.0 .85 1 .15]);
    uicontrol(scsgeneralp,'Style','text','String','Survey #  ','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.02 .75 .1 .2],'ForegroundColor','blue');
    uicontrol(scsgeneralp,'Style','text','String','Name:  ','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.12 .75 .33 .2],'ForegroundColor','blue');
    uicontrol(scsgeneralp,'Style','text','String','P-wave reflection phase number:  ','HorizontalAlignment','center','FontWeight','bold','FontSize',10,'Units','normalized','Position',[.46 .75 .4 .2],'ForegroundColor','blue');
    scspop3=uicontrol(scsgeneralp,'Style','popup','String',{'SCS survey name','Pick uncertainty (s)','Model layer','Ray type (2 reflection)','Wave type (1 P-wave)',...
        'Time correction (s)','Delete whole line'},'FontWeight','bold','FontSize',10,'Units','normalized','Position',[.89 .79 .1 .2],'Callback','');
    scsinputh=uicontrol(scsgeneralp,'Style','edit','String','','HorizontalAlignment','center','FontSize',10,'Units','normalized','Position',[.69 .45 .3 .2]);
    uicontrol(scsgeneralp,'Style','text','String','Shot number vs. model distance table source file: "   "','HorizontalAlignment','left','FontSize',10,'Units','normalized','Position',[.05 .15 0.6 .5]);
    uicontrol(scsgeneralp,'Style','pushbutton','String','Set','Tag','SCS','HorizontalAlignment','center','FontWeight','bold','FontSize',10,...
        'Callback',@setvalue_callback,'Units','normalized','Position',[.89 .15 .1 .25],'ForegroundColor','red');
    % phase table
    uicontrol(scsdisplayp,'Style','text','String','Survey # :     ','HorizontalAlignment','right','FontWeight','bold','FontSize',12,'Units','normalized','Position',[.0 .82 .49 .025],'ForegroundColor','blue');
    scsphasetexth=uicontrol(scsdisplayp,'Style','text','String','Phase # is selected','HorizontalAlignment','left','FontWeight','bold','FontSize',12,'Units','normalized','Position',[.51 .82 .49 .025],'ForegroundColor','blue');
    scssphasesourceh=uicontrol(scsdisplayp,'Style','text','String','Source file: "   "','HorizontalAlignment','left','FontSize',10,'Units','normalized','Position',[.05 .76 0.9 .05]);
    scsphaseh=uitable(scsdisplayp,'Units','normalized','Position',[.0 .0 1 .76],'ColumnName',phasecolname);

    set(txmh,'CloseRequestFcn',@my_closerequest)
    % Initialize some button group properties.
    set(bgh,'SelectedObject',[]);  % No selection
    % make the window visable
    set(displayp,'Visible','on');
    set(controlp,'Visible','on');
    set(txmh,'Visible','on');
end


%% ----- Callback Functions ------%
    function my_closerequest(hObject, eventdata)
        options.Interpreter = 'tex';
        options.Default = 'No';
        selection = questdlg(['\fontsize{14}Do you want to exit ?',char(13,10)','\color{red}Make sure you have saved your work successfully from Database menu !'],...
            'Close Request Function',...
            'Yes','No',options);
        switch selection,
            case 'Yes',
                save('history_txmanager.mat', save_list{:});
                savefig(txmh, 'history_txmanager.fig');
                delete(txmh)
            case 'No'
        end
    end

    function debug_callback(src,event)
        clc
        whos
        assignin('base','OBS',OBS);
        assignin('base','SCS',SCS);
        assignin('base','modelvalues',[modelorigin modelstrike]);
        assignin('base','phasegroup',phasegroup);
        assignin('base','timegroup',timegroup);
        assignin('base','phasecollection',phasecollection);
    end

    function save_callback(src,event)
        if isempty(fullsave)
            [savename savepath]=uiputfile('*.mat');
        else
            [savename savepath]=uiputfile(fullsave);
        end
        if ~isscalar(savename)
            fullsave=fullfile(savepath,savename);
            save(fullsave,save_list{:});
            save('history_txmanager.mat',save_list{:});
            set(txmh,'Name',['tx manager [',fullsave,']']);
            set(ch12,'Enable','on');
        end
    end

    function load_callback(src,event)
        if alreadyload==1;
            selection = questdlg('Before load new database, please save current work.',...
                'Database save suggestion','Save','No save, continue loading','Cancel','Save');
            switch selection
                case 'Save'
                    save_callback;
                case 'No save, continue loading'
                case 'Cancel'
                    return
            end
        end
        if isempty(fullload)
            [loadname loadpath]=uigetfile('*.mat');
        else
            [loadname loadpath]=uigetfile(fullload);
        end
        if ~isscalar(loadname)
            fullload=fullfile(loadpath,loadname);
            s=load (fullload);
            savepath=loadpath;
            savename=loadname;
            fullsave=fullload;
            previoustxin=s.previoustxin;
            preofftablepath=s.preofftablepath;
            prepickpath=s.prepickpath;
            modelorigin=s.modelorigin;
            modelstrike=s.modelstrike;
            OBS=s.OBS;
            SCS=s.SCS;
            phasegroup=s.phasegroup;
            phasecollection=s.phasecollection;
            phaseIDused=s.phaseIDused;
            timegroup=s.timegroup;
            s=[];
            fun_batch_ui_switch({ch13 ch14 ch15 ch41 ch42 ch43 ch44 ch51},'Enable','on');
            fun_batch_ui_switch({ch16 ch18},'Enable','off');
            if size(OBS,2)~=0;
                fun_batch_ui_switch({ch23 ch24},'Enable','on');
                set(rbh1,'Enable','on');
                set(obspop1,'String',fun_make_popup_strings(OBS,'OBS'));
                set(obspop1,'Value',1);
                set(obspop2,'String',fun_make_popup_strings(OBS(get(obspop1,'Value')).phase,'Phase'));
                set(obspop2,'Value',1);
                fun_update_all_panel_display(OBS(get(obspop1,'Value')),'OBS',{obsp,obsdisplayp});
            else
                set(rbh1,'Enable','off');
            end
            if size(SCS,2)~=0;
                fun_batch_ui_switch({ch33 ch34},'Enable','on');
                set(rbh2,'Enable','on');
                set(scspop1,'String',fun_make_popup_strings(SCS,'SCS'));
                set(scspop1,'Value',1);
                set(scspop2,'String',fun_make_popup_strings(SCS(get(scspop1,'Value')).phase,'Phase'));
                set(scspop2,'Value',1);
                fun_update_all_panel_display(SCS(get(scspop1,'Value')),'SCS',{scsp,scsdisplayp});
            else
                set(rbh2,'Enable','off');
            end
            set(txmh,'Name',['tx manager [',fullload,']']);
            % save('history_txmanager.mat',save_list{:});
            set(ch12,'Enable','on');
            set(oxh,'String',num2str(modelorigin(1)));
            set(oyh,'String',num2str(modelorigin(2)));
            set(strikeh,'String',num2str(modelstrike));
        end
        alreadyload=1;
    end

    function bgh_SelectionChangeFcn(hObject,eventdata)
        switch get(eventdata.NewValue,'Tag') % Get Tag of selected object.
            case 'OBS'
                fun_batch_ui_switch({displayp,scsp,scsdisplayp},'Visible','off');
                fun_batch_ui_switch({obsp,obsdisplayp},'Visible','on');
            case 'SCS'
                fun_batch_ui_switch({displayp,obsp,obsdisplayp,scsp,scsdisplayp},'Visible','off');
                fun_batch_ui_switch({scsp,scsdisplayp},'Visible','on');
        end
    end

    function createbytxin_callback(src,event)
        if isempty(previoustxin);
            [txname,txpath]=uigetfile('*.in');
        else
            [txname,txpath]=uigetfile(previoustxin);
        end
        if ~isscalar(txname)  % when cacel, txname==0
            txfull=fullfile(txpath,txname);
            previoustxin=txfull;
            % save ('history_txmanager.mat');
            [OBS,SCS,phasecollection,phaseIDused,phasegroup,timegroup]=fun_create_by_tx_in(txfull,phaseIDused);
            alreadyload=1;
            fun_batch_ui_switch({ch13 ch14 ch15 ch16 ch18 ch41 ch42 ch43 ch44 ch51},'Enable');
            fun_batch_ui_switch({ch23 ch24},'Enable');
            fun_batch_ui_switch({ch33 ch34},'Enable');
            if size(OBS,2)~=0;
                set(rbh1,'Enable','on');
                set(obspop1,'String',fun_make_popup_strings(OBS,'OBS'));
                set(obspop2,'String',fun_make_popup_strings(OBS(get(obspop1,'Value')).phase,'Phase'));
                fun_update_all_panel_display(OBS(1),'OBS',{obsp,obsdisplayp});
            end
            if size(SCS,2)~=0;
                set(rbh2,'Enable','on');
                set(scspop1,'String',fun_make_popup_strings(SCS,'SCS'));
                set(scspop2,'String',fun_make_popup_strings(SCS(get(scspop1,'Value')).phase,'Phase'));
                fun_update_all_panel_display(SCS(1),'SCS',{scsp,scsdisplayp})
            end
        end
        % save ('history_txmanager.mat');
    end

    function scspop1_callback(src,event)
        popstrings=fun_make_popup_strings(SCS(get(scspop1,'Value')).phase,'Phase');
        set(scspop2,'String',popstrings);
        if length(popstrings)<get(scspop2,'Value');
            set(scspop2,'Value',1);
        end
        fun_update_all_panel_display(SCS(get(scspop1,'Value')),'SCS',{scsp,scsdisplayp});
    end

    function scspop2_callback(src,event)
        phasenumber=get(src,'Value');
        scsnumber=get(scspop1,'Value');
        if isempty(SCS(scsnumber).phase)
            set(scsphaseh,'Data',[]);
        else
            set(scsphaseh,'Data',SCS(scsnumber).phase{phasenumber});
        end
        if isempty(SCS(scsnumber).remarks)
            remarks='';
        else
            remarks=SCS(scsnumber).remarks{phasenumber};
        end
        set(scssphasesourceh,'String',['Source file: "',SCS(scsnumber).phasefile{phasenumber},'"; REMARKS: ',remarks]);
        set(scsphasetexth,'String',['Phase #',num2str(phasenumber),' (ID ',num2str(SCS(scsnumber).phaseID(1,phasenumber)),...
             ', Time group ',num2str(SCS(scsnumber).phaseID(2,phasenumber)),') is selected']);% scsphasetexth
    end

    function obspop1_callback(src,event)
        popstrings=fun_make_popup_strings(OBS(get(obspop1,'Value')).phase,'Phase');
        set(obspop2,'String',popstrings);
        if length(popstrings)<get(obspop2,'Value');
            set(obspop2,'Value',1);
        end
        fun_update_all_panel_display(OBS(get(obspop1,'Value')),'OBS',{obsp,obsdisplayp});
    end

    function obspop2_callback(src,event)
        phasenumber=get(src,'Value');
        obsnumber=get(obspop1,'Value');
        set(obsphaseh,'Data',OBS(obsnumber).phase{phasenumber});
        if isempty(OBS(obsnumber).remarks)
            remarks='';
        else
            remarks=OBS(obsnumber).remarks{phasenumber};
        end
        set(obsphasesourceh,'String',['Source file: "',OBS(obsnumber).phasefile{phasenumber},'"; REMARKS: ',remarks]);
        [ray,wave]=deal('');
        switch OBS(obsnumber).phase{phasenumber}(1,8);
            case 1
                ray='Refraction';
            case 2
                ray='Reflection';
            case 3
                ray='Head';
        end
        switch OBS(obsnumber).phase{phasenumber}(1,9);
            case 1
                wave='P-wave';
            case 2
                wave='S-wave';
        end
        set(obsphasetexth,'String',['Phase #',num2str(phasenumber),' (ID ',num2str(OBS(obsnumber).phaseID(1,phasenumber)),...
            ', Time group ',num2str(OBS(obsnumber).phaseID(2,phasenumber)),') is selected (',ray,' ',wave,')']);% obsphasetexth
    end

    function addtxin_callback(src,event)
        if isempty(previoustxin);
            [txname,txpath]=uigetfile('*.in');
        else
            [txname,txpath]=uigetfile(previoustxin);
        end
        if ~isscalar(txname)  % when cacel, txname==0
            txfull=fullfile(txpath,txname);
            previoustxin=txfull;
            % save ('history_txmanager.mat');
            [OBS,SCS,phasecollection,phaseIDused,phasegroup,timegroup]=fun_import_tx_in(txfull,OBS,SCS,phasecollection,phaseIDused,phasegroup,timegroup);
            if size(OBS,2)~=0;
                fun_batch_ui_switch({ch23 ch24 ch43 ch44},'Enable','on');
                set(rbh1,'Enable','on');
                set(obspop1,'String',fun_make_popup_strings(OBS,'OBS'));
                set(obspop2,'String',fun_make_popup_strings(OBS(get(obspop1,'Value')).phase,'Phase'));
                fun_update_all_panel_display(OBS(get(obspop1,'Value')),'OBS',{obsp,obsdisplayp});
            end
            if size(SCS,2)~=0;
                fun_batch_ui_switch({ch33 ch34 ch43 ch44},'Enable','on');
                set(rbh2,'Enable','on');
                set(scspop1,'String',fun_make_popup_strings(SCS,'SCS'));
                set(scspop2,'String',fun_make_popup_strings(SCS(get(scspop1,'Value')).phase,'Phase'));
                fun_update_all_panel_display(SCS(get(scspop1,'Value')),'SCS',{scsp,scsdisplayp});
            end
        end
        % save ('history_txmanager.mat');
    end

    function importoffset_callback(src,event)
        tag=get(src,'Tag');
        [OBS,SCS,preofftablepath]=fun_import_offset_table(OBS,SCS,preofftablepath,tag,obspop1,scspop1);
        switch tag;
            case 'create';
                fun_batch_ui_switch({ch13 ch14 ch15 ch16 ch18 ch41 ch42 ch51},'Enable');
                alreadyload=1;
                fun_batch_ui_switch({ch33 ch34},'Enable');
                fun_batch_ui_switch({ch23 ch24},'Enable');
                if size(OBS,2)~=0;
                    set(rbh1,'Enable','on');
                    set(obspop1,'String',fun_make_popup_strings(OBS,'OBS'));
                    set(obspop2,'String',fun_make_popup_strings(OBS(get(obspop1,'Value')).phase,'Phase'));
                    fun_update_all_panel_display(OBS(1),'OBS',{obsp,obsdisplayp});
                end
                if size(SCS,2)~=0;
                    set(rbh2,'Enable','on');
                    set(scspop1,'String',fun_make_popup_strings(SCS,'SCS'));
                    set(scspop2,'String',fun_make_popup_strings(SCS(get(scspop1,'Value')).phase,'Phase'));
                    fun_update_all_panel_display(SCS(1),'SCS',{scsp,scsdisplayp})
                end
            case 'OBS';
                if size(OBS,2)~=0;
                    fun_batch_ui_switch({ch23 ch24 ch43 ch44},'Enable','on');
                    set(rbh1,'Enable','on');
                    set(obspop1,'String',fun_make_popup_strings(OBS,'OBS'));
                    set(obspop2,'String',fun_make_popup_strings(OBS(get(obspop1,'Value')).phase,'Phase'));
                    fun_update_all_panel_display(OBS(get(obspop1,'Value')),'OBS',{obsp,obsdisplayp});
                end
            case 'SCS';
                if size(SCS,2)~=0;
                    fun_batch_ui_switch({ch33 ch34 ch43 ch44},'Enable','on');
                    set(rbh2,'Enable','on');
                    set(scspop1,'String',fun_make_popup_strings(SCS,'SCS'));
                    set(scspop2,'String',fun_make_popup_strings(SCS(get(scspop1,'Value')).phase,'Phase'));
                    fun_update_all_panel_display(SCS(get(scspop1,'Value')),'SCS',{scsp,scsdisplayp});
                end
        end
        % save ('history_txmanager.mat');
    end

    function edit_callback(src,event)
        switch get(src,'Tag');
            case 'ox'
                modelorigin(1)=str2num(get(src,'String'));
            case 'oy'
                modelorigin(2)=str2num(get(src,'String'));
            case 'strike'
                modelstrike=str2num(get(src,'String'));
        end
    end

    function setvalue_callback(src,event)
        selection = questdlg('Do you want to make the change ?','Request confirm','Yes','No','No');
        switch selection
            case 'Yes'
                switch get(src,'Tag');
                    case 'OBS'
                        obsnumber=get(obspop1,'Value');
                        phasenumber=get(obspop2,'Value');
                        ss=get(obsinputh,'String');
                        switch get(obspop3,'Value')
                            case 1; % 'OBS name'
                                OBS(obsnumber).name=strtrim(ss);
                                set(obspop1,'String',fun_make_popup_strings(OBS,'OBS'));
                            case 2; % '[ X Y Z Scale ]'
                                OBS(obsnumber).XYZ=sscanf(ss,'%f');
                            case 3; % '[ Latitude Longitude ]'
                                OBS(obsnumber).LatLon=sscanf(ss,'%f');
                            case 4; % 'Pick uncertainty (s)'
                                OBS(obsnumber).phase{phasenumber}(:,3)=sscanf(ss,'%f');
                            case 5; % 'Model layer'
                                OBS(obsnumber).phase{phasenumber}(:,7)=sscanf(ss,'%f');
                            case 6; % 'Ray type (1 refraction, 2 refelction, 3 head wave'
                                OBS(obsnumber).phase{phasenumber}(:,8)=sscanf(ss,'%f');
                            case 7; % 'Wave type (1 P-wave, 2 S-wave)'
                                OBS(obsnumber).phase{phasenumber}(:,9)=sscanf(ss,'%f');
                            case 8; % 'Time correction (s)'},
                                OBS(obsnumber).phase{phasenumber}(:,12)=sscanf(ss,'%f');
                            case 9; % delete line
                               OBS(obsnumber).phase{phasenumber}(sscanf(ss,'%f'),:)=[];
                        end
                        fun_update_all_panel_display(OBS(obsnumber),'OBS',{obsp,obsdisplayp});
                    case 'SCS'
                        scsnumber=get(scspop1,'Value');
                        phasenumber=get(scspop2,'Value');
                        ss=get(scsinputh,'String');
                        switch get(scspop3,'Value')
                            case 1
                                SCS(scsnumber).name=strtrim(ss);
                                set(scspop1,'String',fun_make_popup_strings(SCS,'SCS'));
                            case 2
                                SCS(scsnumber).phase{phasenumber}(:,3)=sscanf(ss,'%f');
                            case 3
                                SCS(scsnumber).phase{phasenumber}(:,7)=sscanf(ss,'%f');
                            case 4
                                SCS(scsnumber).phase{phasenumber}(:,8)=2;
                            case 5
                                SCS(scsnumber).phase{phasenumber}(:,9)=1;
                            case 6
                                SCS(scsnumber).phase{phasenumber}(:,12)=sscanf(ss,'%f');
                            case 7; % delete line
                                SCS(scsnumber).phase{phasenumber}(ss,:)=[];
                        end
                        fun_update_all_panel_display(SCS(get(scspop1,'Value')),'SCS',{scsp,scsdisplayp});
                end
            case 'No'
        end
    end

    function timegrouptool_callback(src,event)
        [OBS,SCS,timegroup,phasegroup]=fun_set_timegroup(OBS,SCS,timegroup,phasegroup);
        if size(OBS,2)~=0;
            fun_batch_ui_switch({ch23 ch24 ch43 ch44},'Enable','on');
            set(rbh1,'Enable','on');
            set(obspop1,'String',fun_make_popup_strings(OBS,'OBS'));
            set(obspop1,'Value',1);
            set(obspop2,'String',fun_make_popup_strings(OBS(get(obspop1,'Value')).phase,'Phase'));
            set(obspop2,'Value',1);
            fun_update_all_panel_display(OBS(get(obspop1,'Value')),'OBS',{obsp,obsdisplayp});
        else
            set(rbh1,'Enable','off');
            set(obsphaseh,'Data',[]);
        end
        if size(SCS,2)~=0;
            fun_batch_ui_switch({ch33 ch34 ch43 ch44},'Enable','on');
            set(rbh2,'Enable','on');
            set(scspop1,'String',fun_make_popup_strings(SCS,'SCS'));
            set(scspop1,'Value',1);
            set(scspop2,'String',fun_make_popup_strings(SCS(get(scspop1,'Value')).phase,'Phase'));
            set(scspop2,'Value',1);
            fun_update_all_panel_display(SCS(get(scspop1,'Value')),'SCS',{scsp,scsdisplayp});
        else
            set(rbh2,'Enable','off');
            set(scsphaseh,'Data',[]);
        end
    end

    function maketxtool_callback(src,event)
        [OBS,SCS,phasegroup]=fun_txin_maker(OBS,SCS,phasegroup,timegroup);
    end

    function help_callback(src,event)
    end

    function export_callback(src,event)
    end

    function maintain_callback(src,event)
        [OBS,SCS,timegroup,phasegroup,phasecollection]=fun_maintain_toolbox(OBS,SCS,modelorigin,modelstrike,timegroup,phasegroup,phasecollection);
        if size(OBS,2)~=0;
            fun_batch_ui_switch({ch23 ch24 ch43 ch44},'Enable','on');
            set(rbh1,'Enable','on');
            set(obspop1,'String',fun_make_popup_strings(OBS,'OBS'));
            set(obspop1,'Value',1);
            set(obspop2,'String',fun_make_popup_strings(OBS(get(obspop1,'Value')).phase,'Phase'));
            fun_update_all_panel_display(OBS(get(obspop1,'Value')),'OBS',{obsp,obsdisplayp});
        else
            set(rbh1,'Enable','off');
            set(obsphaseh,'Data',[]);
        end
        if size(SCS,2)~=0;
            fun_batch_ui_switch({ch33 ch34 ch43 ch44},'Enable','on');
            set(rbh2,'Enable','on');
            set(scspop1,'String',fun_make_popup_strings(SCS,'SCS'));
            set(scspop1,'Value',1);
            set(scspop2,'String',fun_make_popup_strings(SCS(get(scspop1,'Value')).phase,'Phase'));
            fun_update_all_panel_display(SCS(get(scspop1,'Value')),'SCS',{scsp,scsdisplayp});
        else
            set(rbh2,'Enable','off');
            set(scsphaseh,'Data',[]);
        end
        if size(OBS,2)==0 && size(SCS,2)==0;
            fun_batch_ui_switch({ch16 ch18},'Enable','on');
            fun_batch_ui_switch({ch23 ch24 ch33 ch34 ch41 ch42 ch43 ch44},'Enable','off');
        end
    end

    function importpicks_callback(src,event)
        selection = questdlg(['The "And time picks" function only support the *.dat files of horizons exported from Kingdom and ',...
            'in the specific format of GeoQuest-CARD-IMAGE7. It is actual a ASCII file and can be opened with any text editor. ',...
            'Currently, the input file can only have one OBS or SCS line, but can contain several horizon picks belong to this OBS/SCS line.'],...
            'Import OBS/SCS picks','Go on','Cancel','Cancel');
        switch selection
            case 'Go on'
                [pickname,pickpath]=uigetfile(fullfile(prepickpath,'*.dat'));
                if ~isscalar(pickname)  % when cacel, name==0
                    pickfull=fullfile(pickpath,pickname);
                    prepickpath=pickpath;
                    % save ('history_txmanager.mat');
                    [OBS,SCS,phaseIDused,phasecollection,timegroup]=fun_pick_import(pickfull,OBS,SCS,phaseIDused,phasecollection,timegroup);
                    if size(OBS,2)~=0;
                        fun_batch_ui_switch({ch23 ch24 ch43 ch44},'Enable','on');
                        set(rbh1,'Enable','on');
                        set(obspop1,'String',fun_make_popup_strings(OBS,'OBS'));
                        set(obspop2,'String',fun_make_popup_strings(OBS(get(obspop1,'Value')).phase,'Phase'));
                        fun_update_all_panel_display(OBS(get(obspop1,'Value')),'OBS',{obsp,obsdisplayp});
                    end
                    if size(SCS,2)~=0;
                        fun_batch_ui_switch({ch33 ch34 ch43 ch44},'Enable','on');
                        set(rbh2,'Enable','on');
                        set(scspop1,'String',fun_make_popup_strings(SCS,'SCS'));
                        set(scspop2,'String',fun_make_popup_strings(SCS(get(scspop1,'Value')).phase,'Phase'));
                        fun_update_all_panel_display(SCS(get(scspop1,'Value')),'SCS',{scsp,scsdisplayp});
                    end
                end
                % save ('history_txmanager.mat');
            case 'Cancel'
        end
    end

end % function tool_tx_manager
